package com.ztrue.framework.context;

import com.ztrue.framework.Config;
import com.ztrue.framework.core.command.CommandExecuteContext;
import com.ztrue.framework.core.command.CommandMessage;
import com.ztrue.framework.core.command.ICommand;
import com.ztrue.framework.core.domain.IRepository;
import com.ztrue.framework.exception.NotFoundException;
import com.ztrue.common.log.Logger;
import com.ztrue.common.properties.Prop;
import com.ztrue.common.properties.Proper;
import com.ztrue.common.utilities.Assert;

/**
 * 命令总线
 * 接收待处理命令并将命令发送至对应的命令处理器
 *
 * @author zhangw
 * @date 2016/11/6 22:11
 * @version: 1.0
 */
public abstract class CommandBus {
    private static final Logger logger = Logger.getLogger(CommandBus.class);
    protected static final IProcessingMessageHandler commandHandleChannel;
    protected static final IRepository repository;

    /**
     * 初始化一个命令处理总线
     *
     * @param commandMessageHander 命令消息处理对象
     */
    static {
        Prop prop = Proper.use(Config.CONFIG_PATH);
        if (prop == null) {
            logger.error("无法找到基础配置文件");
            throw new NotFoundException("无法找到基础配置文件");
        }
        String ibus = prop.get("command.queue.channel", "local");
        switch (ibus) {
            case "local":
                commandHandleChannel = new DefaultProcessingCommandHandler();
                break;
            default:
                commandHandleChannel = null;
        }
        Assert.notNull(commandHandleChannel, "无法创建命令处理总线");
        repository = ApplicationContextProvider.APPLICATIONCONTEXT.getRepository();
    }

    /**
     * 执行一个命令
     *
     * @param command 命令对象
     */
    public static void send(ICommand command) {
        commandHandleChannel.handler(command);
    }
}